package com.sinodata.bsm.center.web.action.performance;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.Page;
import com.sinodata.bsm.center.bean.ResBean;
import com.sinodata.bsm.center.bean.ResTypeBean;
import com.sinodata.bsm.center.cache.CollectFieldCache;
import com.sinodata.bsm.center.cache.PropertyCache;
import com.sinodata.bsm.center.service.performance.PropValueService;
import com.sinodata.bsm.center.service.resource.CollectTaskService;
import com.sinodata.bsm.center.service.resource.PropertyService;
import com.sinodata.bsm.center.util.spring.SpringContextHolder;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.constants.DataTypeConstants;
import com.sinodata.bsm.common.vo.CollectField;
import com.sinodata.bsm.common.vo.CollectTask;
import com.sinodata.bsm.common.vo.Property;
import com.sinodata.bsm.common.vo.PropertyValue;

import edu.emory.mathcs.backport.java.util.Collections;

/**
 * 
 * <p>
 * Description: 指标查询 
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * Jul 5, 2012 3:15:48 PM          wangyazhou        1.0         To create
 * </p>
 * 
 * @since 
 * @see
 */
@SuppressWarnings("rawtypes")
public class PropQueryAction extends BaseAction {

    private static Logger logger = Logger.getLogger(PropQueryAction.class);

    private Long id;

    @Autowired
    private PropValueService propService;

    @Autowired
    private PropertyCache propertyCache;

    @Autowired
    private PropertyService propertyService;

    @Autowired
    CollectTaskService collectTaskService;

    private static final long serialVersionUID = 1L;

    public static final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static final SimpleDateFormat sf2 = new SimpleDateFormat("yyyyMMddHHmmss");

    @SuppressWarnings("unchecked")
    public String queryProp() {
        try {
            String resId = request.getParameter("resId");
            String dimen = request.getParameter("dimen");
            String propIds = request.getParameter("propIds");
            String timeSection = request.getParameter("timeSection");
            String beginDate = request.getParameter("beginDate");
            String endDate = request.getParameter("endDate");

            String[] props = propIds.split("[,]");

            int[] propids = new int[props.length];
            for (int i = 0; i < props.length; i++) {
                Property p = propertyCache.get(Long.parseLong(props[i]));
                int ii = p.getStore();
                propids[i] = ii;
            }

            if (dimen == null || dimen.length() == 0) {
                dimen = "0";
            }

            Page<PropertyValue> page = new Page<PropertyValue>();
            page.setPageNo(Integer.valueOf(request.getParameter("iDisplayStart")) / Integer.valueOf(request.getParameter("iDisplayLength")) + 1);
            page.setPageSize(Integer.valueOf(request.getParameter("iDisplayLength")));

            page = propService.getPropValuesByPage(Long.parseLong(resId), page, propids, DateGeneric.genericStartDate(timeSection, beginDate), DateGeneric.getnericEndDate(dimen, timeSection, endDate), dimen);

            List<PropertyValue> list = page.getRows();
            JSONObject json = new JSONObject();
            JSONArray propArray = new JSONArray();
            //构建原始指标数据
            if ("0".equals(dimen)) {
                for (PropertyValue pv : list) {
                    JSONObject obj = new JSONObject();
                    obj.element("time", formateDate(pv.getTime(), timeSection));
                    for (int i = 0; i < propids.length; i++) {
                        String val = pv.getValues()[i];
                        obj.element(props[i], val.length() == 0 ? "&nbsp;" : val);
                    }
                    propArray.add(obj);
                }
            } else {
                for (PropertyValue pv : list) {
                    JSONObject obj = new JSONObject();
                    obj.element("time", formateDate(pv.getTime(), timeSection));
                    for (int i = 0; i < propids.length; i++) {
                        obj.element(props[i] + "_AVG", pv.getValues()[4 * i] == null ? "&nbsp;" : pv.getValues()[4 * i]);
                        obj.element(props[i] + "_MAX", pv.getValues()[4 * i + 2] == null ? "&nbsp;" : pv.getValues()[4 * i + 2]);
                        obj.element(props[i] + "_MIN", pv.getValues()[4 * i + 3] == null ? "&nbsp;" : pv.getValues()[4 * i + 3]);
                    }
                    propArray.add(obj);
                }
            }

            json.element("aaData", propArray);
            json.element("iTotalRecords", page.getTotal());
            json.element("iTotalDisplayRecords", page.getTotal());

            //System.out.println(json.toString());
            Struts2Utils.renderText(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 
     * demo:2012-08-23 17:13:27.0
     * @param d
     * @param timeSection
     * @return
     */
    private String formateDate(Date d, String timeSection) {
        //        if("0".equals(timeSection)){
        //            return d.toString().substring(11, d.toString().length() - 2);
        //        }else if("1".equals(timeSection)){
        //            return d.toString().substring(8, d.toString().length()-2);
        //        }else if("2".equals(timeSection)){
        //            return d.toString().substring(8, d.toString().length()-2);
        //        }else if("3".equals(timeSection)){
        //            return d.toString().substring(8, d.toString().length()-2);
        //        }else if("4".equals(timeSection)){
        //            return d.toString().substring(5, d.toString().length()-2);
        //        }else {
        //            return d.toString();
        //        }
        return d.toString().replaceAll("-", "/").substring(5, d.toString().length() - 2);
    }

    /**
     * 返回一个资源所有的指标列表
     * tyep 1:数值和字符型  2:数值型
     * @return
     */
    public String getPropList() {
        String resId = request.getParameter("resId");

        String type = request.getParameter("type");

        JSONArray propArray = new JSONArray();
        try {
            ResBean rbean = ResBean.get(Long.parseLong(resId));
            if (rbean == null) {
                return null;
            }
            ResTypeBean bean = ResTypeBean.get(rbean.res().getResTypeId());
            if (bean == null) {
                return null;
            }

            List<CollectTask> resTaskList = collectTaskService.findByResId(rbean.res().getId());//采集器实例
            List<CollectTask> taskList = new ArrayList<CollectTask>(); //显示的结果
            List<CollectTask> typelist = collectTaskService.findByResTypeId(bean.resType().getId());
            if (resTaskList != null) {
                taskList.addAll(resTaskList);
                for (int i = 0; typelist != null && i < typelist.size(); i++) {
                    CollectTask task = typelist.get(i);
                    boolean hasConf = false;
                    for (CollectTask task2 : resTaskList) {
                        if (task2.getResTypeTaskId() != null && task.getId().longValue() == task2.getResTypeTaskId()) {
                            hasConf = true;
                        }
                    }
                    if (!hasConf) {
                        taskList.add(task);
                    }
                }
            } else if (typelist != null) {
                taskList.addAll(typelist);
            }

            //批量采集时采集任务在父资源上
            taskList.addAll(collectTaskService.findFatherTaskByResId(Long.parseLong(resId)));
            CollectFieldCache collectFieldCache = SpringContextHolder.getBean(CollectFieldCache.class);
            Set<Long> propSet = new HashSet<Long>();
            for (CollectTask task : taskList) {
                List<CollectField> fields = collectFieldCache.get(task.getId());
                if (fields != null) {
                    for (CollectField field : fields) {
                        propSet.add(field.getProp());
                    }
                }
            }

            List<Property> properties = bean.properties();

            List<Property> definedProperty = propertyService.findPropertyByResId(Long.parseLong(resId));
            if (definedProperty != null) {
                properties.addAll(definedProperty);
            }

            Collections.sort(properties, new Comparator<Property>() {
                @Override
                public int compare(Property o1, Property o2) {
                    return o1.getDisplay() - o2.getDisplay();
                }
            });
            for (Property p : properties) {
                int val = p.getDataTypeId().intValue();
                if (propSet.contains(p.getId())) {
                    if ("1".equals(type)) {
                        if (val == DataTypeConstants.DATA_TYPE_NUM || val == DataTypeConstants.DATA_TYPE_STRING || val == DataTypeConstants.DATA_TYPE_BOOLEAN || val == DataTypeConstants.DATA_TYPE_DATE) {
                            JSONObject json = new JSONObject();
                            json.element("id", p.getId());
                            json.element("name", p.getName());
                            propArray.add(json);
                        } else {
                            continue;
                        }
                    }
                    if ("2".equals(type)) {
                        if (val == DataTypeConstants.DATA_TYPE_NUM) {
                            JSONObject json = new JSONObject();
                            json.element("id", p.getId());
                            json.element("name", p.getName());
                            propArray.add(json);
                        } else {
                            continue;
                        }
                    }

                } else {
                    continue;
                }
            }
            Struts2Utils.renderText(propArray.toString());
        } catch (Exception e) {
            Struts2Utils.renderText(propArray.toString());
        }

        return null;
    }

    /**
     * 只显示数值型指标
     * @return
     */
    public String getNumPropList() {
        String resId = request.getParameter("resId");
        try {
            ResBean rbean = ResBean.get(Long.parseLong(resId));
            if (rbean == null) {
                return null;
            }
            ResTypeBean bean = ResTypeBean.get(rbean.res().getResTypeId());
            if (bean == null) {
                return null;
            }

            List<CollectTask> resTaskList = collectTaskService.findByResId(rbean.res().getId());//采集器实例
            List<CollectTask> taskList = new ArrayList<CollectTask>(); //显示的结果
            List<CollectTask> typelist = collectTaskService.findByResTypeId(bean.resType().getId());
            if (resTaskList != null) {
                taskList.addAll(resTaskList);
                for (int i = 0; typelist != null && i < typelist.size(); i++) {
                    CollectTask task = typelist.get(i);
                    boolean hasConf = false;
                    for (CollectTask task2 : resTaskList) {
                        if (task2.getResTypeTaskId() != null && task.getId().longValue() == task2.getResTypeTaskId()) {
                            hasConf = true;
                        }
                    }
                    if (!hasConf) {
                        taskList.add(task);
                    }
                }
            } else if (typelist != null) {
                taskList.addAll(typelist);
            }
            CollectFieldCache collectFieldCache = SpringContextHolder.getBean(CollectFieldCache.class);
            Set<Long> propSet = new HashSet<Long>();
            for (CollectTask task : taskList) {
                List<CollectField> fields = collectFieldCache.get(task.getId());
                if (fields != null) {
                    for (CollectField field : fields) {
                        propSet.add(field.getProp());
                    }
                }
            }

            List<Property> properties = bean.properties();

            List<Property> definedProperty = propertyService.findPropertyByResId(Long.parseLong(resId));
            if (definedProperty != null) {
                properties.addAll(definedProperty);
            }

            JSONArray propArray = new JSONArray();
            for (Property p : properties) {
                if (p.getDataTypeId().intValue() == DataTypeConstants.DATA_TYPE_NUM) {
                    JSONObject json = new JSONObject();
                    json.element("id", p.getId());
                    json.element("name", p.getName());
                    propArray.add(json);
                } else {
                    continue;
                }
            }
            Struts2Utils.renderText(propArray.toString());
        } catch (Exception e) {
            logger.error(e);
        }

        return null;
    }

    public String getCalPropList() {

        return null;
    }

    //进入性能查看页面
    @Override
    public String execute() throws Exception {
        String format = "yyyy-MM-dd ";
        SimpleDateFormat simple = new SimpleDateFormat(format);
        String endDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 23:59";
        String beginDate = simple.format(new Date(new Date().getTime() - 3600000 * 24 * 7)) + "00:00";
        Struts2Utils.setRequestAttribute("beginDate", beginDate);
        Struts2Utils.setRequestAttribute("endDate", endDate);
        Struts2Utils.setRequestAttribute("id", id);
        return SUCCESS;
    }

    @Override
    public Object getModel() {
        return null;
    }

    @Override
    public String list() throws Exception {
        return SUCCESS;
    }

    @Override
    public String input() throws Exception {
        return null;
    }

    @Override
    public String save() throws Exception {
        return null;
    }

    @Override
    public String delete() throws Exception {
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {

    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}
